import json
import time
import requests
from other.quantify import FB_URL_2
from requ.conn import bb_conn, fb_connect, ss_comm, db_uid, db_conn
from sql.sql_conn import Mysql_data
from sql.sql_state import select_gun, insert_duiwu, update_duiwu, dllete_duiwu


class Gunqiu(Mysql_data):

    def bb_gunpiu_duiwu(self, bisai_fb_bb_duiwu='bisai_fb_bb_duiwu'):
        da = []
        # mysql_data = Mysql_Bb()
        bb_getduiwu = select_gun("game_id", 'bisai_get_bb')  # bisai_get_bb
        bb_get_duiwu = self.run_sql(bb_getduiwu)
        bb_get_duiwu = [i[0] for i in bb_get_duiwu]
        bbduiwu = select_gun("BB_game_id", bisai_fb_bb_duiwu)  # bisai_fb_bb_duiwu
        bb_duiwu = self.run_sql(bbduiwu)
        bb_duiwu = [i[0] for i in bb_duiwu]
        # print(type(bb_get_duiwu[0]))
        # print(type(bb_duiwu[0]))

        ws = bb_conn()
        data_2 = {
            "command": "get",
            "params": {
                "source": "betting",
                "what": {
                    "competition": [
                        "name"
                    ],
                    "region": [
                        "name"
                    ],
                    "game": [
                        "team1_name",
                        "team2_name",
                        "start_ts",
                        "info",
                        "stats"

                    ]
                },
                "where": {
                    "market": {
                        "@or": [
                            {
                                "display_key": "ODD/EVEN"
                            },
                            {
                                "display_key": "WINNER"
                            },
                            {
                                "display_key": "HANDICAP",
                                "main_order": {
                                    "@in": [
                                        1,
                                        2,
                                        3,
                                        4
                                    ]
                                }
                            },
                            {
                                "display_key": "CORNERWINNER"
                            },
                            {
                                "display_key": "CORNERHANDICAP"
                            },
                            {
                                "display_key": "CORNERTOTALS",
                                "main_order": {
                                    "@in": [
                                        1,
                                        2,
                                        3,
                                        4
                                    ]
                                }
                            },
                            {
                                "display_key": "CORNERODD/EVEN"
                            },
                            {
                                "display_key": "TOTALS",
                                "main_order": {
                                    "@in": [
                                        1,
                                        2,
                                        3,
                                        4
                                    ]
                                }
                            }
                        ]
                    },
                    "sport": {
                        "id": 1
                    },
                    "game": {
                        "type": 1
                    }
                },
                "subscribe": "true"
            },
            "rid": int(round(time.time(), 5) * 100000)
        }
        ws.send(json.dumps(data_2))
        ret = ws.recv()
        res_data = json.loads(ret.encode().decode("utf8"))  # 'unicode-escape'
        apk = res_data["data"]["data"]["region"]

        region_id_list = [i for i in apk]

        for region_id in region_id_list:
            team1_reg_name = apk[region_id]["name"]  # 地区
            competition = apk[region_id]["competition"]

            for competition_id in competition:
                bbliansai_name = competition[competition_id]["name"]  # 联赛名字
                game = competition[competition_id]["game"]
                for game_id in game:
                    start_ts = game[game_id]["start_ts"]  # 时间戳
                    bbtime = time.strftime('%Y-%m-%d %H:%M', time.localtime(start_ts))  # 时间
                    zhu_name = game[game_id]["team1_name"]
                    ke_name = game[game_id]["team2_name"]

                    stats = game[game_id]["stats"]
                    info_score = game[game_id]["info"]["score1"] + ":" + game[game_id]["info"]["score2"]  # 比分
                    try:
                        yellow_card = str(stats["yellow_card"]["team1_value"]) + ":" + str(
                            stats["yellow_card"]["team2_value"])  # 黄牌
                    except:
                        yellow_card = -1
                    try:
                        red_card = str(stats["red_card"]["team1_value"]) + ":" + str(
                            stats["red_card"]["team2_value"])  # 红牌
                    except:
                        red_card = -1
                    try:
                        corner = str(stats["corner"]["team1_value"]) + ":" + str(stats["corner"]["team2_value"])  # 角球
                    except:
                        corner = -1
                    try:
                        current_game_time = game[game_id]["info"]["current_game_time"]  # 比赛进行时间
                    except:
                        current_game_time = -1

                    bb_list = bbtime, bbliansai_name, zhu_name, ke_name, team1_reg_name, info_score, yellow_card, red_card, corner, current_game_time, game_id, region_id, competition_id

                    if int(game_id) not in bb_get_duiwu:
                        # print(bb_duiwu_data)
                        if int(game_id) not in bb_duiwu:
                            # print(type(game_id))
                            print("bb", bb_list)
                            da.append(bb_list)
                    if int(game_id) in bb_get_duiwu:
                        tal = 'info_score', 'yellow_card', 'red_card', 'corner', 'current_game_time'
                        data_tal = info_score, yellow_card, red_card, corner, current_game_time
                        for k, v in zip(tal, data_tal):
                            up = update_duiwu("bisai_get_bb", k, 'game_id')
                            self.run_sql(up, (v, game_id))
                            # print(up)
                    if int(game_id) in bb_duiwu:
                        up_2 = update_duiwu("bisai_fb_bb_duiwu", "BB_corner", "BB_game_id")
                        self.run_sql(up_2, (corner, game_id))
                        # print(up_2)
        if da != []:
            in_data = insert_duiwu("bisai_get_bb")
            self.run_sql(in_data, da)
            # print(in_data)
        print("BB完成")

    def ss_gunqiu(self):
        data = ss_comm()
        events = data['events']
        fb_getduiwu = select_gun("game_id", 'bisai_get_ss')  # bisai_get_bb
        fb_get_duiwu = self.run_sql(fb_getduiwu)
        fb_get_duiwu = [i[0] for i in fb_get_duiwu]

        fbduiwu = select_gun("FB_game_id", 'bisai_fb_bb_duiwu')  # bisai_fb_bb_duiwu
        fb_duiwu = self.run_sql(fbduiwu)
        fb_duiwu = [i[0] for i in fb_duiwu]
        ass = []
        for eve in events:
            for eve_data in eve:
                eveid = eve_data['eveid']  # 比赛ID
                dt = eve_data['dt']  # 开赛时间
                bb_time_strp = time.strptime(str(dt), '%Y-%m-%d %H:%M:%S')
                duiwu_time_mk = int(time.mktime(bb_time_strp)) + 3600 * 12
                dt = time.strftime("%Y-%m-%d %X", time.localtime(duiwu_time_mk))
                lgecapt = eve_data['lgecapt']  # 联赛名称
                tacapt = eve_data['tacapt']  # 主队
                tbcapt = eve_data['tbcapt']  # 客队
                if "角球" in tbcapt:
                    continue
                if "加时" in lgecapt or "电竞" in lgecapt or '特别投注' in lgecapt:
                    continue

                try:
                    evetm = eve_data["rbinfo"]["evetm"]  # 时间
                except:
                    print(eve_data)
                    evetm = -1

                rbinfo_scoa_scob = str(eve_data["rbinfo"]["scoa"]) + ":" + str(eve_data["rbinfo"]["scob"])  # 得分
                data_all = dt, lgecapt, tacapt, tbcapt, rbinfo_scoa_scob, evetm, eveid
                if int(eveid) not in fb_get_duiwu:
                    if int(eveid) not in fb_duiwu:
                        ass.append(data_all)
                        print('SS', data_all)

                if int(eveid) in fb_get_duiwu:
                    tal = 'info_score', 'current_game_time'
                    data_tal = rbinfo_scoa_scob, evetm
                    for k, v in zip(tal, data_tal):
                        up = update_duiwu("bisai_get_fb", k, "game_id")
                        self.run_sql(up, (v, eveid))
        if ass:
            ins = insert_duiwu("bisai_get_ss")
            self.run_sql(ins, ass)
            # print(ins)
        print("SS完成")

    def fb_gunpiu_duiwu(self, num=1, bisai_fb_bb_duiwu='bisai_fb_od_duiwu'):
        da = []
        data_b = {
            "languageType": "CMN",
            "current": num,
            "orderBy": 1,
            "isPC": "true",
            "sportId": 1,
            "type": 1
        }
        ss = requests.Session()
        res = fb_connect(FB_URL_2, data_b, ss)

        if res == None:
            return None

        fb_getduiwu = select_gun("game_id", 'bisai_get_fb')  # bisai_get_bb
        fb_get_duiwu = self.run_sql(fb_getduiwu)
        fb_get_duiwu = [i[0] for i in fb_get_duiwu]

        fbduiwu = select_gun("FB_game_id", bisai_fb_bb_duiwu)  # bisai_fb_bb_duiwu
        fb_duiwu = self.run_sql(fbduiwu)
        fb_duiwu = [i[0] for i in fb_duiwu]

        # print(fb_get_duiwu)
        # print(fb_duiwu)
        # print(res)
        text = res['data']['records']
        total = res["data"]["total"] // 50 + 1
        for i in range(len(text)):
            guojia = text[i]["lg"]["rnm"]  # 比赛地区
            bt = text[i]['bt']  # 时间戳
            fb_id = text[i]["id"]  # 比赛id
            time_time = time.strftime('%Y-%m-%d %H:%M', time.localtime(bt / 1000))  # 时间
            liansai_name = text[i]['lg']['na']  # 联赛名
            zhudui_name = text[i]['ts'][0]['na']  # 队名1
            kedui_name = text[i]['ts'][1]['na']  # 队名2
            try:
                nsg_1 = str(text[i]["nsg"][0]["sc"][0]) + ":" + str(text[i]["nsg"][0]["sc"][1])  # 得分
            except:
                nsg_1 = -1
            try:
                nsg_2 = str(text[i]["nsg"][1]["sc"][0]) + ":" + str(text[i]["nsg"][1]["sc"][1])  # 黄牌
            except:
                nsg_2 = -1
            try:
                nsg_3 = str(text[i]["nsg"][2]["sc"][0]) + ":" + str(text[i]["nsg"][2]["sc"][1])  # 红牌
            except:
                nsg_3 = -1
            try:
                nsg_4 = str(text[i]["nsg"][3]["sc"][0]) + ":" + str(text[i]["nsg"][3]["sc"][1])  # 角球
            except:
                nsg_4 = -1
            try:
                mc_s = text[i]["mc"]["s"] // 60  # 比赛进行时间
            except:
                mc_s = -1

            name_list = time_time, liansai_name, zhudui_name, kedui_name, guojia, nsg_1, nsg_2, nsg_3, nsg_4, mc_s, fb_id
            # fb_duiwu_data, fb_duiwu = name_bb_fb("fb")
            # print('******')
            if int(fb_id) not in fb_get_duiwu and name_list not in da:
                if int(fb_id) not in fb_duiwu:
                    print("fb", name_list)
                    da.append(name_list)
            if int(fb_id) in fb_get_duiwu:
                tal = 'info_score', 'yellow_card', 'red_card', 'corner', 'current_game_time'
                data_tal = nsg_1, nsg_2, nsg_3, nsg_4, mc_s
                for k, v in zip(tal, data_tal):
                    up = update_duiwu("bisai_get_fb", k, "game_id")
                    self.run_sql(up, (v, fb_id))
            if int(fb_id) in fb_duiwu:
                up_1 = update_duiwu(bisai_fb_bb_duiwu, "FB_corner", 'FB_game_id')
                print("***")
                self.run_sql(up_1, (nsg_4, fb_id))
                print('----')
                # print(up_1)
        if da != []:
            ins = insert_duiwu("bisai_get_fb")
            # print("***")
            # print(ins)
            # print(da)
            self.run_sql(ins, da)
            # print("-++-++-+--+-+-")
        print("FB完成")
        return total

    def db_guiqiu_duiwu(self, data, bisai_fb_bb_duiwu='bisai_od_bb_duiwu'):  # bisai_fb_od_duiwu
        if bisai_fb_bb_duiwu == 'bisai_od_bb_duiwu':
            BB_game_id = 'FB_game_id'
            BB_corner = 'FB_corner'
        else:
            BB_game_id = 'BB_game_id'
            BB_corner = 'BB_corner'

        data_all = json.loads(data)['data']
        da_duiwu = []
        for data_a in data_all:
            tn = data_a['tn']  # 联赛名
            if 'VS' in tn:
                break
            mhn = data_a['mhn']  # 主队
            man = data_a['man']  # 客队
            try:
                msc = data_a['msc'][0][3:]  # S1 比分？？？？？
                # S12 黄      S5 角球
            except:
                # print(data_a['msc'])
                msc = -1
                # self.msc1 = data_a['msc'][16]  # 时间？？？？？
            self.mid = int(data_a['mid'])

            mgt = int(data_a['mgt'])  # 开赛时间戳
            time_time = time.strftime('%Y-%m-%d %H:%M', time.localtime(mgt / 1000))  # 时间
            msc_msc = data_a['msc']
            yellow_card = -1
            corner = 1
            for msc_l in msc_msc:
                if 'S5|' in msc_l:
                    # print(msc_l)
                    corner = msc_l[3:]
                if 'S12|' in msc_l:
                    # print(msc_l)
                    yellow_card = msc_l[4:]

            db_duiwu = time_time, tn, mhn, man, -1, msc, yellow_card, -1, corner, -1, self.mid, -1, -1
            bb_getduiwu = select_gun("game_id", 'bisai_get_od')  # bisai_get_bb
            bb_get_duiwu = self.run_sql(bb_getduiwu)
            bb_get_duiwu = [i[0] for i in bb_get_duiwu]

            bbduiwu = select_gun(BB_game_id, bisai_fb_bb_duiwu)  # bisai_fb_bb_duiwu
            bb_duiwu = self.run_sql(bbduiwu)
            bb_duiwu = [i[0] for i in bb_duiwu]
            if self.mid not in bb_get_duiwu and db_duiwu not in da_duiwu:
                if self.mid not in bb_duiwu:
                    print("db", db_duiwu)
                    da_duiwu.append(db_duiwu)
            if self.mid in bb_get_duiwu:
                tal = 'info_score', 'yellow_card', 'corner'
                data_tal = msc, yellow_card, corner
                for k, v in zip(tal, data_tal):
                    up = update_duiwu("bisai_get_od", k, "game_id")
                    self.run_sql(up, (v, self.mid))
            if self.mid in bb_duiwu:
                up_1 = update_duiwu(bisai_fb_bb_duiwu, BB_corner, BB_game_id)  # bisai_fb_bb_duiwu
                self.run_sql(up_1, (corner, self.mid))
        if da_duiwu != []:
            ins = insert_duiwu("bisai_get_od")
            self.run_sql(ins, da_duiwu)
        print("OD完成")

    def over_duiwu_delete(self, biao_mane):  #='bb_od'

        if biao_mane == "bb_fb":
            bisai_get_bb = 'bisai_get_bb'
            bisai_get_fb = 'bisai_get_fb'
            bisai_fb_bb_duiwu = 'bisai_fb_bb_duiwu'
        elif biao_mane == "bb_od":
            bisai_get_bb = 'bisai_get_bb'
            bisai_get_fb = 'bisai_get_od'
            bisai_fb_bb_duiwu = 'bisai_od_bb_duiwu'
        elif biao_mane == 'fb_od':
            bisai_get_bb = 'bisai_get_od'
            bisai_get_fb = 'bisai_get_fb'
            bisai_fb_bb_duiwu = 'bisai_fb_od_duiwu'

        bbduiwu_time = select_gun('*', bisai_get_bb)
        fbduiwu_time = select_gun('*', bisai_get_fb)
        bbfb_time = select_gun('id, bisai_time, FB_corner, BB_corner', bisai_fb_bb_duiwu)

        bb_duiwu_time = self.run_sql(bbduiwu_time)
        fb_duiwu_time = self.run_sql(fbduiwu_time)
        bb_fb_time = self.run_sql(bbfb_time)

        # print(bb_duiwu_time)
        # print(fb_duiwu_time)
        # print(bb_fb_time)`

        for i in range(len(bb_duiwu_time)):
            bb_time = bb_duiwu_time[i][1]
            bb_time_strp = time.strptime(str(bb_time), '%Y-%m-%d %H:%M:%S')
            duiwu_time_mk = int(time.mktime(bb_time_strp)) + 3600 * 2
            duiwu_id = bb_duiwu_time[i][0]
            if duiwu_time_mk < time.time():
                dl = dllete_duiwu(bisai_get_bb, 'id')
                self.run_sql(dl, duiwu_id)

            bb_bisai_time = bb_duiwu_time[i][10]
            if int(bb_bisai_time) >= 98:
                dl_1 = dllete_duiwu(bisai_get_bb, 'id')
                self.run_sql(dl_1, duiwu_id)

        for i in range(len(fb_duiwu_time)):
            fb_time = fb_duiwu_time[i][1]
            bb_time_strp = time.strptime(str(fb_time), '%Y-%m-%d %H:%M:%S')
            duiwu_time_mk = int(time.mktime(bb_time_strp)) + 3600 * 2
            duiwu_id = fb_duiwu_time[i][0]
            if duiwu_time_mk < time.time():
                dll = dllete_duiwu(bisai_get_fb, 'id')
                self.run_sql(dll, duiwu_id)

            fb_bisai_time = fb_duiwu_time[i][10]
            if int(fb_bisai_time) >= 98:
                dll_1 = dllete_duiwu(bisai_get_fb, 'id')
                self.run_sql(dll_1, duiwu_id)
        print("-----------------------")
        for i in range(len(bb_fb_time)):
            duiwu_time = bb_fb_time[i][1]
            duiwu_time_strp = time.strptime(str(duiwu_time), '%Y-%m-%d %H:%M:%S')
            duiwu_time_mk = int(time.mktime(duiwu_time_strp)) + 3600 * 2
            duiwu_id = bb_fb_time[i][0]
            if duiwu_time_mk < time.time():
                dlle = dllete_duiwu(bisai_fb_bb_duiwu, 'id')
                self.run_sql(dlle, duiwu_id)
            # 角球是否一样
            if bb_fb_time[i][2] != "0:0" and bb_fb_time[i][3] != "0:0":
                if bb_fb_time[i][2] == bb_fb_time[i][3]:
                    is_corner = 0
                else:
                    is_corner = 1
            else:
                is_corner = 0
            upda = update_duiwu(bisai_fb_bb_duiwu, "is_corner", "id")
            self.run_sql(upda, (is_corner, duiwu_id))
        # 队伍匹配

        duiwu_bb_fb = []
        for i in fb_duiwu_time:
            for j in bb_duiwu_time:
                if bisai_get_bb == 'bisai_get_bb' or bisai_get_bb == 'bisai_get_od':
                    is_num = j[15]
                else:
                    is_num = j[13]

                if i[1] == j[1] and (i[3] == j[3] or i[4] == j[4]) and i[13] != 1 and is_num != 1:

                    # is_mate = 1
                    # bb_mate = update_duiwu(bisai_get_bb, 'is_mate', 'id')
                    # fb_mate = update_duiwu(bisai_get_fb, 'is_mate', 'id')
                    # self.run_sql(bb_mate, (is_mate, j[0]))
                    # self.run_sql(fb_mat
                    # e, (is_mate, i[0]))


                    dllete_bb = dllete_duiwu(bisai_get_bb, 'id')
                    dllete_fb = dllete_duiwu(bisai_get_fb, 'id')
                    self.run_sql(dllete_bb, j[0])
                    self.run_sql(dllete_fb, i[0])

                    if i[9] != "0:0" and j[9] != "0:0":
                        if i[9] == j[9]:
                            is_corner = 0
                        else:
                            is_corner = 1
                    else:
                        is_corner = 0

                    if bisai_get_bb == 'bisai_get_bb' or bisai_get_bb == 'bisai_get_od':
                        duiwu_bbfb = (
                            i[1], i[2], i[3], i[4], j[2], j[3], j[4], i[5], j[5], i[11], j[11], j[12], j[13], i[9],
                            j[9],
                            is_corner)
                    else:
                        duiwu_bbfb = (
                            i[1], i[2], i[3], i[4], j[2], j[3], j[4], i[5], j[5], i[11], j[11], i[9], j[9],
                            is_corner)
                    duiwu_bb_fb.append(duiwu_bbfb)

        # 队伍 mohu 匹配
        # fb_1 = []
        # fb_2 = []
        # bb_1 = []
        # bb_2 = []

        # for i in fb_duiwu_time:
        #     fb_1.append([fb for fb in i[3]])
        #     fb_2.append(([fb for fb in i[4]]))
        #
        # for i in bb_duiwu_time:
        #     bb_1.append([bb for bb in i[3]])
        #     bb_2.append(([bb for bb in i[4]]))

        # duiwu = []

        # for num_fb, i in enumerate(fb_duiwu_time):
        #     if i[12] != 1 and i[13] != 1:
        #         for num_bb, j in enumerate(bb_duiwu_time):
        #             if bisai_get_bb == 'bisai_get_bb':
        #                 is_num = j[15]
        #                 is_num_2 = j[14]
        #             else:
        #                 is_num = j[13]
        #                 is_num_2 = j[12]
        #
        #             if is_num != 1 and is_num_2 != 1:
        #                 if i[1] == j[1] and i[5] == j[5]:
        #                     num_b = 0
        #                     num_f = 0
        #                     if i[9] != "0:0" and j[9] != "0:0":
        #                         if i[9] == j[9]:
        #                             is_corner = 0
        #                         else:
        #                             is_corner = 1
        #                     else:
        #                         is_corner = 0
        #                     for k in fb_1[num_fb]:
        #                         for n in bb_1[num_bb]:
        #                             if k == n:
        #                                 num_f += 1
        #
        #                                 if len(i[3]) > len(j[3]):
        #                                     if num_f / len(i[3]) > 0.6:
        #                                         # is_mate = 1
        #                                         # bb_mate = update_duiwu(bisai_get_bb, 'is_mate', 'id')
        #                                         # fb_mate = update_duiwu(bisai_get_fb, 'is_mate', 'id')
        #                                         # self.run_sql(bb_mate, (is_mate, j[0]))
        #                                         # self.run_sql(fb_mate, (is_mate, i[0]))
        #
        #                                         dllete_bb = dllete_duiwu(bisai_get_bb, 'id')
        #                                         dllete_fb = dllete_duiwu(bisai_get_fb, 'id')
        #                                         self.run_sql(dllete_bb, j[0])
        #                                         self.run_sql(dllete_fb, i[0])
        #
        #                                         if bisai_get_bb == 'bisai_get_bb':
        #                                             data = i[1], i[2], i[3], i[4], j[2], j[3], j[4], i[5], j[5], i[11], \
        #                                                 j[
        #                                                     11], j[12], j[13], i[9], j[9], is_corner
        #                                         else:
        #                                             data = i[1], i[2], i[3], i[4], j[2], j[3], j[4], i[5], j[5], i[11], \
        #                                                 j[11], i[9], j[9], is_corner
        #
        #                                         if data not in duiwu_bb_fb:  # fb_data not in fb_ser and bb_data not in bb_ser:
        #                                             # print("000",data)
        #                                             if i not in duiwu and j not in duiwu:
        #                                                 duiwu.append(i)
        #                                                 duiwu.append(j)
        #
        #                                                 # dllete_duiwu(bisai_get_bb, 'id')
        #                                                 # dllete_duiwu(bisai_get_fb, 'id')
        #                                                 duiwu_bb_fb.append(data)
        #
        #                                 else:
        #                                     if num_f / len(j[3]) > 0.6:
        #                                         # is_mate = 1
        #                                         # bb_mate = update_duiwu(bisai_get_bb, 'is_mate', 'id')
        #                                         # fb_mate = update_duiwu(bisai_get_fb, 'is_mate', 'id')
        #                                         # self.run_sql(bb_mate, (is_mate, j[0]))
        #                                         # self.run_sql(fb_mate, (is_mate, i[0]))
        #
        #                                         dllete_bb = dllete_duiwu(bisai_get_bb, 'id')
        #                                         dllete_fb = dllete_duiwu(bisai_get_fb, 'id')
        #                                         self.run_sql(dllete_bb, j[0])
        #                                         self.run_sql(dllete_fb, i[0])
        #
        #                                         if bisai_get_bb == 'bisai_get_bb':
        #                                             data = i[1], i[2], i[3], i[4], j[2], j[3], j[4], i[5], j[5], i[11], \
        #                                                 j[
        #                                                     11], j[12], j[13], i[9], j[9], is_corner
        #                                         else:
        #                                             data = i[1], i[2], i[3], i[4], j[2], j[3], j[4], i[5], j[5], i[11], \
        #                                                 j[
        #                                                     11], i[9], j[9], is_corner
        #
        #                                         if data not in duiwu_bb_fb:  # fb_data not in fb_ser and bb_data not in bb_ser:
        #                                             # print("001",data)
        #                                             if i not in duiwu and j not in duiwu:
        #                                                 duiwu.append(i)
        #                                                 duiwu.append(j)
        #                                                 # dllete_duiwu(bisai_get_bb, 'id')
        #                                                 # dllete_duiwu(bisai_get_fb, 'id')
        #                                                 duiwu_bb_fb.append(data)
        #
        #                     for l in fb_2[num_fb]:
        #                         for m in bb_2[num_bb]:
        #                             if l == m:
        #                                 num_b += 1
        #
        #                                 if len(i[4]) > len(j[4]):
        #                                     if num_b / len(i[4]) > 0.6:
        #                                         # is_mate = 1
        #                                         # bb_mate = update_duiwu(bisai_get_bb, 'is_mate', 'id')
        #                                         # fb_mate = update_duiwu(bisai_get_fb, 'is_mate', 'id')
        #                                         # self.run_sql(bb_mate, (is_mate, j[0]))
        #                                         # self.run_sql(fb_mate, (is_mate, i[0]))
        #
        #                                         dllete_bb = dllete_duiwu(bisai_get_bb, 'id')
        #                                         dllete_fb = dllete_duiwu(bisai_get_fb, 'id')
        #                                         self.run_sql(dllete_bb, j[0])
        #                                         self.run_sql(dllete_fb, i[0])
        #
        #                                         if bisai_get_bb == 'bisai_get_bb':
        #                                             data = i[1], i[2], i[3], i[4], j[2], j[3], j[4], i[5], j[5], i[11], \
        #                                                 j[
        #                                                     11], j[12], j[13], i[9], j[9], is_corner
        #                                         else:
        #                                             data = i[1], i[2], i[3], i[4], j[2], j[3], j[4], i[5], j[5], i[11], \
        #                                                 j[
        #                                                     11], i[9], j[9], is_corner
        #
        #                                         if data not in duiwu_bb_fb:  # fb_data not in fb_ser and bb_data not in bb_ser:
        #                                             # print("002",data)
        #                                             if i not in duiwu and j not in duiwu:
        #                                                 duiwu.append(i)
        #                                                 duiwu.append(j)
        #                                                 # dllete_duiwu(bisai_get_bb, 'id')
        #                                                 # dllete_duiwu(bisai_get_fb, 'id')
        #                                                 duiwu_bb_fb.append(data)
        #                                 else:
        #                                     if num_b / len(j[4]) > 0.6:
        #                                         # is_mate = 1
        #                                         # bb_mate = update_duiwu(bisai_get_bb, 'is_mate', 'id')
        #                                         # fb_mate = update_duiwu(bisai_get_fb, 'is_mate', 'id')
        #                                         # self.run_sql(bb_mate, (is_mate, j[0]))
        #                                         # self.run_sql(fb_mate, (is_mate, i[0]))
        #
        #                                         dllete_bb = dllete_duiwu(bisai_get_bb, 'id')
        #                                         dllete_fb = dllete_duiwu(bisai_get_fb, 'id')
        #                                         self.run_sql(dllete_bb, j[0])
        #                                         self.run_sql(dllete_fb, i[0])
        #
        #                                         if bisai_get_bb == 'bisai_get_bb':
        #                                             data = i[1], i[2], i[3], i[4], j[2], j[3], j[4], i[5], j[5], i[11], \
        #                                                 j[
        #                                                     11], j[12], j[13], i[9], j[9], is_corner
        #                                         else:
        #                                             data = i[1], i[2], i[3], i[4], j[2], j[3], j[4], i[5], j[5], i[11], \
        #                                                 j[
        #                                                     11], i[9], j[9], is_corner
        #
        #                                         if data not in duiwu_bb_fb:  # fb_data not in fb_ser and bb_data not in bb_ser:
        #                                             # print('003',data)
        #                                             if i not in duiwu and j not in duiwu:
        #                                                 duiwu.append(i)
        #                                                 duiwu.append(j)
        #                                                 # dllete_duiwu(bisai_get_bb, 'id')
        #                                                 # dllete_duiwu(bisai_get_fb, 'id')
        #                                                 duiwu_bb_fb.append(data)

        if duiwu_bb_fb:
            ins = insert_duiwu(bisai_fb_bb_duiwu)
            # print(duiwu_bb_fb)
            # print(ins)
            self.run_sql(ins, duiwu_bb_fb)

    def run_gunqiu(self):
        nn = 1
        sql = "SELECT token FROM db_token"
        to = self.run_sql(sql)[0][0]
        while True:
            try:
                uid = db_uid(to)
                da = db_conn(uid, to)
                self.db_guiqiu_duiwu(da)
                break
            except Exception as e:
                print('DB', e)
                time.sleep(2)
                nn += 1
                if nn == 5:
                    break
        self.bb_gunpiu_duiwu()
        # total = self.fb_gunpiu_duiwu()
        # if total > 1:
        #     for i in range(2, total + 1):
        #         self.fb_gunpiu_duiwu(i)
        # self.ss_gunqiu()
        self.over_duiwu_delete('bb_od')  # bb_ss

        # self.results_data()
        # self.fb_results_data()
        print("ok")

    def results(self):
        # time.strftime('%Y-%m-%d %H:%M', time.localtime(1686801600))
        # int(time.mktime(time.strptime('2023-06-15 12:00:00', '%Y-%m-%d %H:%M:%S')))
        t1 = int(time.time())
        t2 = time.strftime('%Y-%m-%d', time.localtime(t1))
        t2 = '{} 12:00:00'.format(t2)
        t3 = int(time.mktime(time.strptime(t2, '%Y-%m-%d %H:%M:%S')))

        if t1 > t3:
            from_date = t3
        else:
            from_date = t3 - 24 * 3600
        # print(from_date)
        r_data = {
            "command": "get_result_games",
            "params": {
                "is_date_ts": 1,
                "sport_id": 1,
                "competition_id": "",
                "live": 0,
                "from_date": from_date,
                "to_date": int(time.time())
            },
            "rid": int(time.time() * 100000)
        }
        return r_data

    # BB赛果
    def results_data(self):
        sql_game_id = select_gun('game_id,bisai_time', 'bb_results')
        sql_game_id = self.run_sql(sql_game_id)

        sql_game_time = [i[1] for i in sql_game_id]
        sql_game_id = [i[0] for i in sql_game_id]
        try:
            r_data = self.results()
            ws = bb_conn()
            ws.send(json.dumps(r_data))
            game_data = ws.recv()
            ws.close()
        except Exception as e:
            print('results_data:*', e)
            return

        games_game = json.loads(game_data)["data"]["games"]["game"]
        data_all = []
        t1 = time.time()
        # print(games_game)
        for game in games_game:
            region_name = game["region_name"]  # 国家
            competition_name = game["competition_name"]  # 联赛名
            team1_name = game["team1_name"]  # 主
            team2_name = game["team2_name"]  # 客
            date = game["date"]  # 开赛时间
            date_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(date))
            game_id = game["game_id"]  # 比赛Id
            scores = game["scores"][:3]  # 全场
            scores_ban = game["scores"][5:-1]  # 半场
            g_data = date_time, region_name, competition_name, team1_name, team2_name, scores_ban, scores, game_id
            if int(game_id) not in sql_game_id:
                data_all.append(g_data)
            # 修改
            if date + 3 * 3600 > t1:
                sql_scores_ban = update_duiwu('bb_results', 'scores_ban', 'game_id')
                sql_scores = update_duiwu('bb_results', 'scores', 'game_id')
                self.run_sql(sql_scores_ban, (scores_ban, game_id))
                self.run_sql(sql_scores, (scores, game_id))

        # 删除
        time_num = len(sql_game_time)
        for tb1 in range(time_num):
            tb4 = str(sql_game_time[tb1])
            # print(tb4)
            tb2 = int(time.mktime(time.strptime(tb4, '%Y-%m-%d %H:%M:%S')))
            tb3 = int(time.time() - 3600 * 24 * 3)
            if tb2 < tb3:
                aa = sql_game_id[tb1]
                # self.run("bb_results", aa, mm=4)
                sql_dl = dllete_duiwu('bb_results', 'game_id')
                self.run_sql(sql_dl, aa)
                # print(aa)

        print("BB", len(data_all))
        if data_all:
            sql_data = insert_duiwu("bb_results")
            self.run_sql(sql_data, data_all)

    # FB赛果conn
    def fb_results_all(self):
        url = 'https://iapi.ccapykdsd.com/v1/match/matchResultList'
        t1 = time.time()
        time_time = time.strftime('%Y-%m-%d', time.localtime(t1))  # 时间
        t3 = int(time.mktime(time.strptime(time_time, '%Y-%m-%d')))
        begin_time = int(t3 * 1000)
        end_time = int((t3 + 24 * 3600) * 1000 - 1)
        r_data = {
            "languageType": "CMN",
            "sportId": 1,
            "beginTime": begin_time,
            "end_time": end_time
        }

        header = {
            'Accept': 'application/json, text/plain, */*',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh,zh-CN;q=0.9',
            # 'Authorization': 'tt_mPX35LRkT1qMyIGAjwi08Lnt21LjuHzo.002e955f0069e30fb9e77722ac603c97',
            'Connection': 'keep-alive',
            'Content-Length': '84',
            'Content-Type': 'application/json;charset=UTF-8',
            'Host': 'iapi.ccapykdsd.com',
            'Origin': 'https://ipc.ccpoldsfd.com',
            'Referer': 'https://ipc.ccpoldsfd.com/',
            'Sec-Ch-Ua': '"Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"',
            'Sec-Ch-Ua-Mobile': '?0',
            'Sec-Ch-Ua-Platform': '"Windows"',
            'Sec-Fetch-Dest': 'empty',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Site': 'cross-site',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
        }
        mm = 0
        while True:
            try:
                res = requests.post(url=url, json=r_data, headers=header, timeout=5)  # , proxies=PROXIES
                break
            except Exception as e:
                print('FB连接异常：', e)
                print("FB正在重新连接...fb_results_all")
                mm += 1
                if mm == 5:
                    return None
        print("FB已连接")
        # print("**")
        res_data = res.json()
        # print(res_data)
        return res_data

    def fb_results(self, matchId):
        for game_id in matchId:
            url_2 = 'https://iapi.ccapykdsd.com/v1/match/matchResultInfo'
            r_data = {
                "languageType": "CMN",
                "matchId": game_id
            }
            header = {
                'Accept': 'application/json, text/plain, */*',
                'Accept-Encoding': 'gzip, deflate, br',
                'Accept-Language': 'zh,zh-CN;q=0.9',
                # 'Authorization': 'tt_mPX35LRkT1qMyIGAjwi08Lnt21LjuHzo.002e955f0069e30fb9e77722ac603c97',
                'Connection': 'keep-alive',
                'Content-Length': '84',
                'Content-Type': 'application/json;charset=UTF-8',
                'Host': 'iapi.ccapykdsd.com',
                'Origin': 'https://ipc.ccpoldsfd.com',
                'Referer': 'https://ipc.ccpoldsfd.com/',
                'Sec-Ch-Ua': '"Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"',
                'Sec-Ch-Ua-Mobile': '?0',
                'Sec-Ch-Ua-Platform': '"Windows"',
                'Sec-Fetch-Dest': 'empty',
                'Sec-Fetch-Mode': 'cors',
                'Sec-Fetch-Site': 'cross-site',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
            }
            mm = 0
            while True:
                try:
                    res = requests.post(url=url_2, json=r_data, headers=header, timeout=2)  # , proxies=PROXIES
                    break
                except Exception as e:
                    print('FB连接异常：', e)
                    print("FB正在重新连接...fb_results")
                    mm += 1
                    if mm == 5:
                        return None
            # print("FB已连接")
            res_data = res.json()
            game_data = res_data["data"]["nsg"]
            for sc in game_data:
                pe = sc["pe"]
                tyg = sc["tyg"]
                if pe == 1002 and tyg == 5:
                    try:
                        nsg_sc = str(sc["sc"][0]) + ":" + str(sc["sc"][1])
                        # print(nsg_sc)
                        # self.run("fb_results", [nsg_sc, game_id], "scores_ban", mm=3)
                        sql_scores = update_duiwu('fb_results', 'scores_ban', 'game_id')
                        self.run_sql(sql_scores, (nsg_sc, game_id))
                    except Exception as e:
                        print('nsg_sc', e)

    def fb_results_data(self):
        # sql_id = self.run("fb_results", [], mm=2)
        sql_id = select_gun('game_id, bisai_time', 'fb_results')
        sql_id = self.run_sql(sql_id)
        sql_time = [i[1] for i in sql_id]
        sql_id = [i[0] for i in sql_id]
        f_results_data = self.fb_results_all()
        all_data = f_results_data["data"]
        r_data = []
        id_list = []
        for game in all_data:
            game_id = game["id"]
            time_bt = game["bt"]
            t1 = time.time()
            time_time = time.strftime('%Y-%m-%d %H:%M', time.localtime(time_bt / 1000))

            lg_rnm = game["lg"]["rnm"]  # 国家
            lg_na = game["lg"]["na"]  # 联赛
            ts_na_0 = game['ts'][0]["na"]  # 比赛名
            ts_na_1 = game['ts'][1]["na"]  # 比赛名
            nsg_sc_ban = -1
            nsg_sc = -1
            game_data = game["nsg"]
            for sc in game_data:
                pe = sc["pe"]
                tyg = sc["tyg"]
                if pe == 1002 and tyg == 5:
                    nsg_sc_ban = str(sc["sc"][0]) + ":" + str(sc["sc"][1])
                if pe == 1001 and tyg == 5:
                    nsg_sc = str(sc["sc"][0]) + ":" + str(sc["sc"][1])

            g_data = time_time, lg_rnm, lg_na, ts_na_0, ts_na_1, nsg_sc_ban, nsg_sc, game_id

            if int(game_id) not in sql_id:
                r_data.append(g_data)
                # print(g_data)
            if t1 < (time_bt / 1000) + (2.5 * 3600):
                id_list.append(game_id)
                sql_scores = update_duiwu('fb_results', 'scores', 'game_id')
                self.run_sql(sql_scores, (nsg_sc, game_id))
                # self.run("fb_results", [nsg_sc, game_id], 'scores', mm=3)
        # 删除·
        time_num = len(sql_time)
        for tt1 in range(time_num):
            tt4 = str(sql_time[tt1])
            tt2 = int(time.mktime(time.strptime(tt4, '%Y-%m-%d %H:%M:%S')))
            tt3 = int(time.time() - 3600 * 24 * 3)
            if tt2 < tt3:
                aa = sql_id[tt1]
                # self.run("fb_results", aa, mm=4)
                sql_dl = dllete_duiwu('fb_results', 'game_id')
                self.run_sql(sql_dl, aa)
                # print(aa)

        print("FB", len(r_data))
        if r_data:
            # self.run("fb_results", r_data)
            sql_data = insert_duiwu("fb_results")
            self.run_sql(sql_data, r_data)
        if id_list:
            self.fb_results(id_list)


if __name__ == '__main__':
    while True:
        try:
            run = Gunqiu()
            run.run_gunqiu()
            time.sleep(120)
        except Exception as e:
            print("run: ", e)
            time.sleep(120)
